import { message } from 'antd';
import * as types from './actionTypes';
import { getCartList } from '@/api/cart';
import { customerList } from '@/api/order';
import { formatNumTo2, totalDays } from '@/utils';

// 加入购物车前，提示日期选择
export const setDatePickerOpen = (open) => {
    return dispatch => {
        dispatch({
            type: types.SET_DATE_PICKER_OPEN,
            open
        })
    }
}


// 获取购物车商品
export const getCartListData = (v) => {
    return dispatch => {
        getCartList().then(res => {
            const { code, data } = res;
            if(code === 0 && data){
                dispatch({
                    type: types.GET_CART_LIST_DATA,
                    total: data?.total || 0,
                    cartList: data?.goodsCartActivityItemDTO || []
                })
            }else{
                message.error(res.message);
            }
        })
    }
}

// 选中购物车数据
export const modifyCartListData = (list) => {
    return dispatch => {
        // 选中商品数量和总价格
        let number = 0, price = 0;
        if(list){
            // 更新数据
            dispatch({
                type: types.MODIFY_CART_LIST_DATA,
                cartList: list
            });
            list.forEach(data => {
                const { goodsCartActivityListDTO } = data;
                goodsCartActivityListDTO.forEach(g => {
                    const { amount, salePrice } = g;
                    if(g.checked){
                        number += amount;
                        if(g.projectId == 3){
                            price += amount*salePrice*totalDays(g.startDate, g.endDate) || 0;
                        }else{
                            price += amount*salePrice || 0;
                        }
                    }
                })
            });
        }
        dispatch({
            type: types.CHECKED_LIST_CART_DATA,
            checkedNum: number,
            checkedPrice: formatNumTo2(price)
        })
    }
}

// 全选/全不选
export const allCheckCartListData = (checked) => {
    return dispatch => {
        dispatch({
            type: types.All_CHECK_CART_LIST_DATA,
            checked
        })
    }
}

// 实际支付价格/优惠价格
export const setRealPayPrice = ({totalPrice, realPayPrice, reducePrice}) => {
    return dispatch => {
        dispatch({
            type: types.REAL_PAY_PRICE,
            totalPrice,
            realPayPrice: realPayPrice < 0 ? 0 : realPayPrice,
            reducePrice
        })
    }
}

// 获取游客信息
export const getCustomerList = () => {
    return dispatch => {
        customerList().then(res => {
            const { code, data } = res;
            if (code === 0 && data) {
                dispatch({
                    type: types.GET_CUSTOMER_LIST,
                    data
                })
            }
        })
    }
}

// 填充联系人信息
export const fillContactForm = (data) => {
    return dispatch => {
        dispatch({
            type: types.FILL_IN_CONTACT_FORM,
            data
        })
    }
}